<template>
  <div>
    <top current="register"></top>
    <div class="main-content login">
      <div class="login-main">
        <el-form class="lm-top lm-top_reg" :label-position="labelPosition" ref="form" :model="form" label-width="80px">
          <el-form-item>
            <span class="user-span">用户注册</span>
          </el-form-item>
          <el-form-item prop="phone" :rules="vType('mobile','手机号码',true,'blur')" label="手机号码">
            <el-input ref="phone" v-model="form.phone" placeholder="请输入手机号"></el-input>
          </el-form-item>
          <el-form-item prop="verifyCode" class="el-item_yzm" :rules="vType('','验证码',true,'change')">
            <label slot="label"><span>验&#8194;证&#8194;码</span></label>
            <el-input v-model="form.verifyCode" auto-complete="off"
                      placeholder="请输入验证码">
            </el-input>
            <timer-login ref="disabledReg" class="btn btn-default"
                         v-on:run="sendCode(form.phone,'disabledReg')"
                         v-on:stop="setDisabled(false,'disabledReg')"
                         :disabled="disabledReg" :second="60">
            </timer-login>
          </el-form-item>
          <el-form-item prop="password" :rules="vType('pwd','密码',true,'blur')">
            <label slot="label"><span>密&#8194;&#8194;&#8194;&#8194;码</span></label>
            <el-input type="password" v-model="form.password" placeholder="请输入密码"></el-input>
          </el-form-item>
          <el-form-item prop="confirmPassword" :rules="vType('pwd','确认密码',true,'blur')" label="确认密码">
            <el-input type="password" v-model="form.confirmPassword" placeholder="请输入确认密码"></el-input>
          </el-form-item>
          <div>
            <el-checkbox v-model="showXy">我已阅读并同意</el-checkbox>
            <a class="slient-a" @click="showYsxy">《用户隐私政策》</a>
          </div>
          <el-form-item style="margin-top: 12px">
            <el-button type="warning" class="base-btn register-btn" :loading="loading" @click="register">
              注册
            </el-button>
          </el-form-item>
          <div class="lt-bottom">
            <a @click="goLogin">已有账号去登录</a>
          </div>
        </el-form>
      </div>
    </div>
  </div>
</template>


<script>
import top from '../layout/top';
import {geetByCode, sendVeriCode} from '@/api/login/login';
import {mapActions} from 'vuex';
import  '@/utils/gt';
import {Loading} from 'element-ui';
import timerLogin from '../common/yzm'
export default {
  data() {
    return {
      disabledReg:false,
      loading: false,
      labelPosition: 'center',
      form: {
        phone: '',
        password: '',
        confirmPassword:'',
        verifyCode: '',
        appCode: 'WMR',
        productCode: 'WMR'
      },
      isSendSMS: false,
      captchaObj: {},

      showXy: false,
      lastTime: 0
    }
  },
  components: {
    top,timerLogin
  },
  watch: {
    captchaObj:{
      deep: true,
      handler:function (newV,oldV) {
        setTimeout(()=>{
          newV.verify()
        },100)
      }
    }
  },

  methods: {
    ...mapActions(['LoginAction', 'RegisterAction']),
    /***
     * 极验
     * 初始化
     * author：fsg
     */
    initGeet(){
      let _ = this;
      geetByCode({
        phone: this.form.phone
      }).then(response => {
        if (response.code === 200) {
          window.initGeetest({
            challenge: JSON.parse(response.data).challenge,
            gt: JSON.parse(response.data).gt,
            success: JSON.parse(response.data).success,
            offline: false,
            new_captcha: true,
            product: "bind"
          }, _.handler);
        }
      });
    },
    handler(captchaObj) {
      let _ = this;
      captchaObj.onReady(function () {
        captchaObj.appendTo('#captcha');
        _.captchaObj = captchaObj;
      });
      captchaObj.onSuccess(function () {
        _.setDisabled(true,'disabledReg'); //设置按钮不可用
        _.$refs['disabledReg'].start(); //启动倒计时
        _.sendMessage(_.form.phone)
      });
    },
    sendMessage(phone) {
      let _ = this;
      sendVeriCode(phone,'register').then(response => {
        if (response.code === 200) {
          _.isSendSMS = true;
          _.$message.success('验证码已发送！');
        }
      });
    },
    register() {
      let _ = this;
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!!_.isSendSMS) {
            _.passwordSameOrNot();
          } else {
            _.$message({
              message: '请先获取验证码！',
              type: 'warning'
            });
          }
        } else {
          _.formError(_);
        }
      });
    },
    /***
     * 自定义校验
     * 两次输入密码
     * 是否勾选注册协议
     * author：fsg
     */
    passwordSameOrNot(){
      if(this.form.password===this.form.confirmPassword){
        if(!this.showXy){
          this.$message({
            message: '请先勾选用户隐私政策！',
            type: 'warning'
          });
        }else {
          this.validateSuccess();
        }
      }else{
        this.$message({
          message: '两次输入的密码不一致！',
          type: 'warning'
        });
      }
    },
    /***
     * 异常
     * 注册表单
     * author：fsg
     */
    formError(_){
      setTimeout( ()=> {
        _.vTool.showSingleError();
      }, 10);
    },
    /***
     * 提交
     * 注册表单
     * author：fsg
     */
    validateSuccess() {
        let _ = this;
        this.loading = true;
        const {RegisterAction} = this;
        let regParam = {};
        for(let key in this.form){
          if(key!='confirmPassword'){
            regParam[key] = this.form[key]
          }
        }
        RegisterAction(regParam).then(response => {
          _.loading = false;
          if(response.code==200){
            _.regProcess(_, _.form.phone, _.form.password);
          }
        }).catch(e => {
          _.loading = false;
        });
    },
    /***
     * 完成注册后
     * 开始登录
     * author：fsg
     */
    regProcess(_,phone,password){
      let loadingInstance = Loading.service({
        text: '注册成功',
        fullscreen: false,
        target: document.getElementById('autoLogin')
      });
      //默认登录
      setTimeout(()=>{
        loadingInstance.close();
        _.loginSuccess(phone,password);
      },1000);
    },
    /***
     * 完成注册后
     * 自动登录
     * author：fsg
     */
    loginSuccess(phone,password) {
      let _ = this;
      const {LoginAction} = this;
      LoginAction({
        phone: phone,
        password: password
      }).then((data) => {
        _.$router.push({ path: '/' });
      }).catch((e) => {

      });
    },
    /***
     * 点击发送验证码
     * 防止重复点击触发事件
     * author：fsg
     */
    sendCode(val,param){
      if(/^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(val)){
        let now = new Date().valueOf();
        if(this.lastTime == 0){
          this.lastTime = now;
          this.initGeet();
        }else{
          if((now - this.lastTime) > 2000){
            this.lastTime = now;
            this.initGeet();
          }
        }
      }else{
        this.$message({
          message: '请输入正确的手机号！',
          type: 'warning'
        });
      }
    },
    setDisabled(val,param){
      this[param] = val;
    },
    //********隐私政策*********
    showYsxy(){
      window.open(window.location.origin+'/api/jfs/download/agreement/隐私政策.pdf/WMR');
    },
    goLogin(){
      this.$router.push({ path: '/login' });
    }
  }
}
</script>
<style lang="scss">
.btn-default{
  position: absolute;
  right: 2px;
  top: 8px;
  height: 24px!important;
  line-height: 24px!important;
  background: white!important;
  color: #edbb03!important;
}
</style>
